/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.UserDto;
import com.yami.shop.bean.app.param.BindPhoneParam;
import com.yami.shop.bean.app.param.UserInfoParam;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.BalanceLogService;
import com.yami.shop.service.PhoneService;
import com.yami.shop.service.SmsLogService;
import com.yami.shop.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jodd.util.StringUtil;
import lombok.AllArgsConstructor;
import cn.hutool.core.bean.BeanUtil;
import com.yami.shop.common.response.ServerResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author lanhai
 */
@RestController
@RequestMapping("/p/user")
@Tag(name = "用户接口")
@AllArgsConstructor
@Slf4j
public class UserController {

	private final UserService userService;
	private final PhoneService phoneService;
	private final SmsLogService smsLogService;
	private final BalanceLogService balanceLogService;

	
	/**
	 * 查看用户接口
	 */
	@GetMapping("/userInfo")
	@Operation(summary = "查看用户信息" , description = "根据用户ID（userId）获取用户信息")
	public ServerResponseEntity<UserDto> userInfo() {
		String userId = SecurityUtils.getUser().getUserId();
		User user = userService.getById(userId);
		UserDto userDto = BeanUtil.copyProperties(user, UserDto.class);
		return ServerResponseEntity.success(userDto);
	}

	@PutMapping("/setUserInfo")
	@Operation(summary = "设置用户信息" , description = "设置用户信息")
	public ServerResponseEntity<Void> setUserInfo(@RequestBody UserInfoParam userInfoParam) {
		String userId = SecurityUtils.getUser().getUserId();
		User user = new User();
		user.setUserId(userId);
		user.setPic(userInfoParam.getAvatarUrl());
		user.setNickName(userInfoParam.getNickName());
		userService.updateById(user);
		return ServerResponseEntity.success();
	}
	@PostMapping("/BindPhone")
	@Operation(summary = "绑定手机号" , description = "绑定手机号")
	@Transactional(rollbackFor = Exception.class)
	public ServerResponseEntity<Void> BindPhone(@RequestBody BindPhoneParam bindPhoneParam) {
		String userId = SecurityUtils.getUser().getUserId();
		User user = userService.getUserByUserId(userId);
		if(user==null){
			throw new YamiShopBindException("请从公众号中点击菜单进入商城");
		}
		if(StringUtil.isNotBlank(user.getUserMobile())){
			throw new YamiShopBindException("用户已经绑定了手机号，不能再次绑定");
		}
		Phone phone = phoneService.getOne(new LambdaQueryWrapper<Phone>().eq(Phone::getMobile, bindPhoneParam.getMobile()).eq(Phone::getMallid, user.getMallid()));
		if(phone==null){
			throw new YamiShopBindException("您输入的手机号不是商城的用户手机号，请确认您输入了正确的手机号");
		}
		//核对验证码
		SmsLog smsLog=smsLogService.getOne(
				new LambdaQueryWrapper<SmsLog>()
						.eq(SmsLog::getUserPhone, bindPhoneParam.getMobile())
						//.eq(SmsLog::getMobileCode, bindPhoneParam.getValidCode())
						.eq(SmsLog::getUserId,userId)
		);
		if(smsLog==null){
			throw new YamiShopBindException("短信服务出错！");
		}
		if(!smsLog.getMobileCode().equals(bindPhoneParam.getValidCode())){
			throw new YamiShopBindException("您输入的难码不正确！");
		}

		if(StringUtil.isBlank(user.getUserMobile())){
			if(phone.getBalanceUsed()==0) {
				log.info("===========user.getBalance()=" + user.getBalance());
				log.info("===========phone.getBalance()=" + phone.getBalance());
				BigDecimal r = user.getBalance().add(phone.getBalance());
				log.info("================add=" + user.getBalance().add(phone.getBalance()));
				log.info("================r=" + r);
				user.setBalance(r);  //第一次绑定手机号，才能加余额
				log.info("===========user.getBalance()=" + user.getBalance());
				phone.setBalanceUsed(1);
				phoneService.updateById(phone);
			}
		}
		user.setUserMobile(bindPhoneParam.getMobile());

		userService.updateById(user);
		return ServerResponseEntity.success();
	}

	@GetMapping("/balanceLogs")
	//public ServerResponseEntity<IPage<BalanceLog>> pageByBalanceLog(PageParam<BalanceLog> page) {
	public ServerResponseEntity<List<BalanceLog>> balanceLogs() {
		String userId = SecurityUtils.getUser().getUserId();
		//IPage<BalanceLog> balanceLogPage = balanceLogService.pageByBalanceLog(page,userId);
		List<BalanceLog> balanceLog = balanceLogService.getBalanceLog(userId);
		return ServerResponseEntity.success(balanceLog);
	}

	@GetMapping("/pageByBalanceLog")
	public ServerResponseEntity<IPage<BalanceLog>> pageByBalanceLog(PageParam<BalanceLog> page) {
	//public ServerResponseEntity<List<BalanceLog>> pageByBalanceLog() {
		String userId = SecurityUtils.getUser().getUserId();
		IPage<BalanceLog> balanceLogPage = balanceLogService.pageByBalanceLog(page,userId);
		//List<BalanceLog> balanceLog = balanceLogService.getBalanceLog(userId);
		return ServerResponseEntity.success(balanceLogPage);
	}

}
